<?php
// +----------------------------------------------------------------------
// | ebSIG
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2020 http://www.ebsig.com All rights reserved.
// +----------------------------------------------------------------------
// | Author: liudaojian <liudaojian@ebsig.com>
// +----------------------------------------------------------------------

/**
 * 定时任务中间件
 * @author   liudaojian <liudaojian@ebsig.com>
 * @version 1.0
 */

namespace App\Http\Middleware;

use Closure;

use Carbon\Carbon;

use App\Models\TimedTask;

use App\Models\TimedTaskLog;

class TimedTaskService
{

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

        $task_log_id = $request->input('task_log_id');
        if (!ebsig_is_int($task_log_id)) {
            return '缺少参数：task_log_id';
        }

        $response = $next($request);
        if (method_exists($response, 'getData')) {
            return $this->updateTimedTaskLog($task_log_id, $response->getData(true));
        } else {
            return $this->updateTimedTaskLog($task_log_id, ['message'=>'程序执行出错，App\Http\Middleware\TimedTaskService']);
        }

    }

    /**
     * 更新任务日志
     * @param int $task_log_id 任务日志id
     * @param array $result 结果数组
     * @return string
     */
    public function updateTimedTaskLog($task_log_id, $result)
    {

        $timed_task_log = TimedTaskLog::find($task_log_id);
        if (!$timed_task_log) {
            return 'error';
        }
        $end_time = Carbon::now();
        $total_time = time() - strtotime($timed_task_log->start_time);
        $timed_task_log->end_time = $end_time;
        $timed_task_log->total_time = $total_time;
        $timed_task_log->result = $result['message'];
        $timed_task_log->save();

        return $result['message'];

    }

}
